package br.ucb.musicbay.validator;

import java.util.Locale;

import javax.faces.application.FacesMessage;
import javax.faces.component.UIComponent;
import javax.faces.context.FacesContext;
import javax.faces.validator.FacesValidator;
import javax.faces.validator.Validator;
import javax.faces.validator.ValidatorException;

import br.ucb.musicbay.usuario.UsuarioBO;

@FacesValidator("validatorCpf")
public class CpfValidator implements Validator {

	@Override
	public void validate(FacesContext context, UIComponent comp, Object object) throws ValidatorException {
		UsuarioBO usuarioBo = new UsuarioBO();
		String cpf = object.toString();
		cpf = cpf.replaceAll("\\.", "");
		cpf = cpf.replace("-", "");
		FacesMessage message;
		if (!isCpfValido(cpf)) {
			if(context.getViewRoot().getLocale().equals(new Locale("pt_BR")))
				message = new FacesMessage(FacesMessage.SEVERITY_ERROR,"CPF invalido, favor informe um CPF valido","Informe um CPF valido");
			else
				message = new FacesMessage(FacesMessage.SEVERITY_ERROR,"Invalid CPF, please inform a valid CPF","Inform a valid CPF");
			throw new ValidatorException(message);
		} else if (usuarioBo.verificaItem("cpf",object.toString()) != null) {
			if(context.getViewRoot().getLocale().equals(new Locale("pt_BR")))
				message = new FacesMessage(FacesMessage.SEVERITY_ERROR,"CPF ja cadastrado!","O CPF ja se encontra registrado no sistema");
			else
				message = new FacesMessage(FacesMessage.SEVERITY_ERROR,"CPF already registered!","The CPF informed is already registered in the system");
			throw new ValidatorException(message);
		}

	}

	public static boolean isCpfValido(String strCpf) {
		if (!strCpf.isEmpty()) {
			try {
				int d1, d2;
				int digito1, digito2, resto;
				int digitoCPF;
				String nDigResult;
				d1 = d2 = 0;
				digito1 = digito2 = resto = 0;

				for (int nCount = 1; nCount < strCpf.length() - 1; nCount++) {
					digitoCPF = Integer.valueOf(strCpf.substring(nCount - 1, nCount)).intValue();
					d1 = d1 + (11 - nCount) * digitoCPF;
					d2 = d2 + (12 - nCount) * digitoCPF;
				}
				;
				resto = (d1 % 11);
				if (resto < 2)
					digito1 = 0;
				else
					digito1 = 11 - resto;

				d2 += 2 * digito1;
				resto = (d2 % 11);

				if (resto < 2)
					digito2 = 0;
				else
					digito2 = 11 - resto;

				String nDigVerific = strCpf.substring(strCpf.length() - 2, strCpf.length());
				nDigResult = String.valueOf(digito1) + String.valueOf(digito2);

				return nDigVerific.equals(nDigResult);
			} catch (Exception e) {
				e.printStackTrace();
				return false;
			}
		}
		return false;
	}

}
